package com.example.ywj.myapplication;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * 自定义适配器
 * 1.继承BaseAdapter,并重写4个方法
 */
public class ApplyAdapter extends BaseAdapter {

    private ArrayList<Apply> list ;

    public ApplyAdapter(ArrayList<Apply> list) {
        this.list = list;
    }

    /**
     * 总条目数
     * @return
     */
    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * listView优化
     * 1.复用convertView
     * 2.使用ViewHolder类
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder  viewHolder = null;
        // listview优化1
        if(convertView == null){
            // 获取布局管理器
            LayoutInflater inflater =  LayoutInflater.from(parent.getContext());
            //  布局
            convertView =  inflater.inflate(R.layout.item,null);
            // 从布局中拿控件
            viewHolder = new ViewHolder();
            viewHolder.iv = convertView.findViewById(R.id.item_iv);
            viewHolder.tv = convertView.findViewById(R.id.item_tv);
            convertView.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }

        // 关联数据
        viewHolder.iv.setImageResource(list.get(position).getImgId());
        viewHolder.tv.setText(list.get(position).getName());

        return convertView;
    }

    /**
     * 用于优化listview 2
     */
    class ViewHolder{
       private ImageView iv;
       private TextView tv;
    }


}
